import fetch from 'fermionjs/lib/fetch';

import pkg from '../../../package.json';
import errorCodesBuilder from '../helpers/errorCodesBuilder';
const { name } = pkg;

const errorCodes = errorCodesBuilder();

export default async function isCydEnabled(domain, uid) {
	const {
		log,
		app: {
			model: { User },
			config: {
				[name]: { yunaqDomainCheck },
			},
		},
	} = this;
	this.log.info({ domain, uid }, '检查域名是否使用创宇盾');

	let username;
	try {
		const user = await User.findOne({ _id: uid });
		username = user.username;
	} catch (err) {
		const error = errorCodes['[0E][检查是否使用创宇盾]查询数据库失败'].from(
			err
		);
		this.log.error({ error }, error.rawMessage);
		throw error;
	}

	const api = `${yunaqDomainCheck.api}?${new URLSearchParams({
		domain,
		username,
	})}`;
	return fetch(api, {
		headers: {
			Authorization: `Basic ${yunaqDomainCheck.credentials}`,
			'user-agent':
				'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36',
		},
	})
		.then(resp => {
			this.log.debug({ domain, resp }, '域名是否使用创宇盾');
			if (resp.status === 'success' && resp.msg === 'success') {
				return true;
			}
			return false;
		})
		.catch(err => {
			const error = errorCodes['[0E]检查是否使用创宇盾失败'].from(err);
			log.error({ error, uid, domain, api }, error.rawMessage);
			return null;
		});
}
